#!/bin/bash

#  helper script: create ROM images for a given system, with GRUB payload
#
#	Copyright (C) 2020,2021 Leah Rowe <info@minifree.org>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# This script assumes that the working directory is the root
# of git or release archive

[ "x${DEBUG+set}" = 'xset' ] && set -v
set -u -e

# it is assumed that no other work will be done on the ROM
# after calling this function. therefore this function is "final"
moverom() {
    rompath="$1"
    newrompath="$2"
    cuttype="$3"

    printf "\nCreating new ROM image: %s\n" "${newrompath}"

    if [ "${cuttype}" = "4MiB IFD BIOS region" ]; then
        dd if=${rompath} of=${newrompath} bs=1 skip=$[$(stat -c %s ${rompath}) - 0x400000] count=4194304
    else
        mv ${rompath} ${newrompath}
    fi

    for romsize in 4 8 16; do
        if [ "${cuttype}" = "${romsize}MiB ICH9 IFD NOR flash" ]; then
            if [ ! -f "descriptors/ich9m/ich9fdgbe_${romsize}m.bin" ]; then
                ./build descriptors ich9m
            fi
            dd if=descriptors/ich9m/ich9fdgbe_${romsize}m.bin of=${newrompath} bs=1 count=12k conv=notrunc
        fi
        if [ "${cuttype}" = "${romsize}MiB ICH9 IFD NOGBE NOR flash" ]; then
            if [ ! -f "descriptors/ich9m/ich9fdnogbe_${romsize}m.bin" ]; then
                ./build descriptors ich9m
            fi
            dd if=descriptors/ich9m/ich9fdnogbe_${romsize}m.bin of=${newrompath} bs=1 count=4k conv=notrunc
        fi
    done

    if [ "${cuttype}" = "i945 laptop" ]; then
        dd if=${newrompath} of=top64k.bin bs=1 skip=$[$(stat -c %s ${newrompath}) - 0x10000] count=64k
        dd if=top64k.bin of=${newrompath} bs=1 seek=$[$(stat -c %s ${newrompath}) - 0x20000] count=64k conv=notrunc
        rm -f top64k.bin
    fi
}

if (( $# != 1 )); then
	printf "Usage: ./build osboot roms boardname\n"
	printf "Example: ./build osboot roms default\n"
	printf "You need to specify exactly 1 argument\n"
	exit 1
fi

board="${1}"

if [ ! -d "resources/coreboot/${board}" ]; then
    printf "build/roms: Target %s does not exist in the osboot build system. Skipping build.\n" "${board}"
    exit 1
fi

if [ ! -f "resources/coreboot/${board}/board.cfg" ]; then
    printf "build/roms: Target %s does not have a board.cfg. Skipping build.\n" "${board}"
    exit 1
fi

cbtree="undefined"
romtype="normal" # optional parameter in board.cfg. "normal" is default
arch="undefined"
# Disable all payloads by default.
# board.cfg files have to specifically enable [a] payload(s)
payload_grub="n"
payload_grub_withseabios="n" # seabios chainloaded from grub
payload_grub_withtianocore="n" # tianocore chainloaded from grub
payload_seabios="n"
payload_tianocore="n"
# Override the above defaults using board.cfg
source "resources/coreboot/${board}/board.cfg"
if [ "${cbtree}" = "undefined" ]; then
    printf "build/roms: Target %s does not define a coreboot tree. Skipping build.\n" "${board}"
    exit 1
fi
if [ "${arch}" = "undefined" ]; then
    printf "build/roms: Target %s does not define a CPU type. Skipping build.\n" "${board}"
    exit 1
fi

if [ "${payload_grub_withseabios}" = "y" ] \
        || [ "${payload_grub_withtianocore}" = "y" ]; then
    payload_grub="y"
fi
if [ "${payload_grub_withseabios}" = "y" ]; then
    payload_seabios="y"
fi
if [ "${payload_grub_withtianocore}" = "y" ]; then
    payload_tianocore="y"
fi
if [ "${payload_grub}" != "y" ] && [ "${payload_seabios}" != "y" ] \
        && [ "${payload_tianocore}" != "y" ]; then
    printf "ERROR build/roms: Target '%s' does not define a payload. Exiting.\n" "${board}"
    exit 1
fi

romdir_grub="bin/grub_${board}"
romdir_seabios="bin/seabios_${board}"
romdir_tianocore="bin/tianocore_${board}"
cbdir="coreboot/${board}"
if [ "${board}" != "${cbtree}" ]; then
    cbdir="coreboot/${cbtree}"
fi
cbfstool="${cbdir}/util/cbfstool/cbfstool"
corebootrom="${cbdir}/build/coreboot.rom"
seavgabiosrom="payload/seabios/seavgabios.bin"
tianocoreelf="payload/tianocore/tianocore.elf"

if [ ! -f "mrc/haswell/mrc.bin" ] && [ "${board}" = "t440p_12mb" ]; then
    ./download mrc
    if [ ! -f "mrc/haswell/mrc.bin" ]; then
        printf "t440p build: mrc.bin missing. Skipping build.\n"
        exit 1
    fi
fi

if [ ! -d "${cbdir}" ]; then
    ./download coreboot ${cbtree}
fi

if [ "${arch}" = "x86_32" ] || [ "${arch}" = "x86_64" ]; then
    if [ ! -d "${cbdir}/util/crossgcc/xgcc/i386-elf/" ]; then
        (
            cd "${cbdir}"
            make crossgcc-i386 # even for 64-bit machines, coreboot builds
                # 32-bit ROM images, so we only need to worry about i386-elf
        )
    fi
fi

if [ "${arch}" != "x86_64" ]; then
    payload_tianocore="n"
    payload_grub_withtianocore="n"
fi

if [ ! -f "${cbfstool}" ]; then
    ./build module cbutils ${cbtree}
fi

if [ ! -f "${tianocoreelf}" ]; then
    if [ "${payload_tianocore}" = "y" ]; then
        ./build payload tianocore
    elif [ "${payload_grub}" = "y" ] \
            && [ "${payload_grub_withtianocore}" = "y" ]; then
        ./build payload tianocore
    fi
fi

if [ ! -f "${seavgabiosrom}" ] \
        || [ ! -f payload/seabios/seabios_libgfxinit.elf ] \
        || [ ! -f payload/seabios/seabios_vgarom.elf ]; then
    if [ "${payload_seabios}" = "y" ]; then
        ./build payload seabios
    elif [ "${payload_grub}" = "y" ] \
            && [ "${payload_grub_withseabios}" = "y" ]; then
        ./build payload seabios
    fi
fi

if [ "${payload_grub}" = "y" ]; then
    [ -d "${romdir_grub}/" ] || mkdir -p "${romdir_grub}/"
    rm -f "${romdir_grub}"/* coreboot.tmp.grub.rom
fi

if [ "${payload_seabios}" = "y" ]; then
    [ -d "${romdir_seabios}/" ] || mkdir -p "${romdir_seabios}/"
    rm -f "${romdir_seabios}"/* coreboot.tmp.seabios.rom
fi

if [ "${payload_tianocore}" = "y" ]; then
    [ -d "${romdir_tianocore}/" ] || mkdir -p "${romdir_tianocore}/"
    rm -f "${romdir_tianocore}"/* coreboot.tmp.tianocore.rom
fi

for displaymode in corebootfb txtmode; do
    for initmode in libgfxinit vgarom; do

        cbcfgpath="resources/coreboot/${board}/config/${initmode}_${displaymode}"
        seabioself="payload/seabios/seabios_${initmode}.elf"

        if [ ! -f "${cbcfgpath}" ]; then
            printf "\nCoreboot config %s_%s for target %s does not exist in the build system. Skipping build.\n" \
                "${initmode}" "${displaymode}" "${board}"
            continue
        fi

        (
            cd "${cbdir}"
            make distclean
        )
        cp "${cbcfgpath}" "${cbdir}"/.config
        
        (
            cd "${cbdir}"
            make
        )

	if [ "${payload_tianocore}" = "y" ]; then
            # tianocore requires vesa framebuffer. will not work in text mode
            if [ "${displaymode}" = "corebootfb" ] && \
                    [ "${arch}" = "x86_64" ]; then
                    # do not include on 32-bit-only machines. this is 64-bit tianocore

                newrompath="${romdir_tianocore}/tianocore_${board}_${initmode}_${displaymode}.rom"
                cp "${corebootrom}" coreboot.tmp.tianocore.rom
                "${cbfstool}" coreboot.tmp.tianocore.rom add-payload -f ${tianocoreelf} -n fallback/payload -c lzma
                moverom "coreboot.tmp.tianocore.rom" "${newrompath}" "${romtype}"
            fi
        fi

        if [ "${payload_grub}" = "y" ] || [ "${payload_seabios}" = "y" ]; then
            if [ "${displaymode}" = "txtmode" ]; then
                if [ ! -f "memtest86plus/memtest.bin" ]; then
                    ./build module memtest86plus
                fi
                "${cbfstool}" "${corebootrom}" add-payload -f memtest86plus/memtest.bin -n img/memtest.bin -c lzma
            fi
        fi

        if [ "${payload_seabios}" = "y" ]; then
            cp "${corebootrom}" coreboot.tmp.seabios.rom
            "${cbfstool}" coreboot.tmp.seabios.rom add-payload -f "${seabioself}" -n fallback/payload -c lzma
            "${cbfstool}" coreboot.tmp.seabios.rom add-int -i 3000 -n etc/ps2-keyboard-spinup
            if [ "${initmode}" = "libgfxinit" ]; then
                "${cbfstool}" coreboot.tmp.seabios.rom add -f "${seavgabiosrom}" -n vgaroms/seavgabios.bin -t raw
            fi

            newrompath="${romdir_seabios}/seabios_${board}_${initmode}_${displaymode}.rom"
            moverom "coreboot.tmp.seabios.rom" "${newrompath}" "${romtype}"
        fi

        if [ "${payload_grub}" = "y" ]; then

            if [ "${payload_grub_withtianocore}" = "y" ]; then
                # also copy it to the generic ROM, which will have GRUB added
                "${cbfstool}" "${corebootrom}" add-payload -f ${tianocoreelf} -n tianocore.elf -c lzma
            fi

            if [ "${payload_grub_withseabios}" = "y" ]; then
                "${cbfstool}" "${corebootrom}" add-payload -f "${seabioself}" -n seabios.elf -c lzma
                if [ "${initmode}" = "libgfxinit" ]; then
                    "${cbfstool}" "${corebootrom}" add -f "${seavgabiosrom}" -n vgaroms/seavgabios.bin -t raw
                fi
                "${cbfstool}" "${corebootrom}" add-int -i 3000 -n etc/ps2-keyboard-spinup
            fi

            for keymapfile in resources/grub/keymap/*; do
                if [ ! -f "${keymapfile}" ]; then
                    continue
                fi
                keymap="${keymapfile##*/}"
		keymap="${keymap%.gkb}"

                grubelf="payload/grub/grub_${keymap}.elf"
                grubcfg="payload/grub/grub_${keymap}_${displaymode}.cfg"
                grubtestcfg="payload/grub/grub_${keymap}_${displaymode}_test.cfg"

                if [ ! -f "${grubelf}" ] || [ ! -f "${grubcfg}" ] \
                    || [ ! -f "${grubtestcfg}" ]; then
                    ./build payload grub
                fi

                cp "${corebootrom}" coreboot.tmp.grub.rom
                "${cbfstool}" coreboot.tmp.grub.rom add-payload -f "${grubelf}" -n fallback/payload -c lzma
                "${cbfstool}" coreboot.tmp.grub.rom add -f "${grubcfg}" -n grub.cfg -t raw
                "${cbfstool}" coreboot.tmp.grub.rom add -f "${grubtestcfg}" -n grubtest.cfg -t raw

                if [ "${displaymode}" = "corebootfb" ]; then
                    "${cbfstool}" coreboot.tmp.grub.rom add -f payload/grub/dejavusansmono.pf2 -n dejavusansmono.pf2 -t raw
                fi

                newrompath="${romdir_grub}/grub_${board}_${initmode}_${displaymode}_${keymap}.rom"
                moverom "coreboot.tmp.grub.rom" "${newrompath}" "${romtype}"
            done

        fi
    done
done

rm -f coreboot.tmp.{tianocore,seabios,grub}.rom

printf "\nDone! Your ROMs are in bin/\n\n"

